package  src.com.network;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private static final int PORT = 8888;
    private final ProductService productService = new ProductService();

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.startServer();
    }
    private void startServer() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，监听端口：" + PORT + "，等待客户端连接...");
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接：" + clientSocket.getInetAddress() + ":" + clientSocket.getPort());

                // 启动新线程处理客户端请求（支持多客户端并发）
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {
            String request = (String) ois.readObject();
            System.out.println("接收到客户端请求：" + request);
            switch (request) {
                case "GET_ALL_PRODUCTS":
                    List<Product> productList = productService.getAllProducts();
                    oos.writeObject(productList);
                    oos.flush();
                    System.out.println("已向客户端返回商品列表，共" + productList.size() + "件商品");
                    break;
                default:
                    oos.writeObject("未知请求：" + request);
                    oos.flush();
                    System.out.println("客户端发送未知请求：" + request);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭：" + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败：" + e.getMessage());
            }
        }
    }
}